package com.winit.websocket.util;

import com.winit.mq.task.TailLogTask;
import com.winit.util.Constants;
import com.winit.util.SysInfoTable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

public class SendMessageUtil {

    private final static Logger logger = LoggerFactory.getLogger(SendMessageUtil.class);

    /**
     * 给所有在线用户发送消息
     *
     * @param message
     */
    public synchronized static void sendMessageToUsers(TextMessage message) {
        for (WebSocketSession session : SysInfoTable.websocketList) {
            try {
                if (session.isOpen()) {
                    session.sendMessage(message);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 给某个用户发送消息
     *
     * @param tokenId
     * @param message
     */
    public synchronized static void sendMessageToUser(String tokenId, TextMessage message,String threadId) {
        logger.info("给指定用户发送消息,tokenId="+tokenId+",threadId="+threadId);
        for (WebSocketSession session : SysInfoTable.websocketList) {
            if (session.getAttributes().get(Constants.WEBSOCKET_SESSION_USERNAME_INDEX).equals(tokenId)) {
                try {
                    if (session.isOpen()) {
                        if(StringUtils.isEmpty(threadId)){
                            session.sendMessage(message);
                            break;
                        }

                        String tid = (String) session.getAttributes().get(Constants.WEBSOCKET_SESSION_THREADID_INDEX);
                        if(StringUtils.isEmpty(tid)){
                            session.getAttributes().put(Constants.WEBSOCKET_SESSION_THREADID_INDEX, threadId);
                        }else{
                            if(!(threadId.equals(tid))){
                                TailLogTask task = SysInfoTable.threadMap.get(tid);
                                logger.info("关闭tail线程，threadId="+tid+";task="+task);
                                if(task != null){
                                    task.shutThread();
                                }
                                SysInfoTable.threadMap.remove(tid);
                                session.getAttributes().remove(Constants.WEBSOCKET_SESSION_THREADID_INDEX);
                                session.getAttributes().put(Constants.WEBSOCKET_SESSION_THREADID_INDEX, threadId);
                            }
                        }
                        session.sendMessage(message);
                    }
                } catch (Exception e) {
                    logger.info("给指定用户发送消息异常,tokenId="+tokenId+",e:"+e.getMessage());
                }
                break;
            }
        }
    }

}
